from collections import OrderedDict

from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse, Http404, JsonResponse, HttpResponseNotFound
from django.utils.http import urlencode
from django.views import View
from news.models import Tag, HotNews, News, Banner
from doc.models import Doc
from course.models import Course, Teacher, CourseCategory
from django.db.models import Count
from django.core.paginator import Paginator, EmptyPage
from utils.response_code import ResultResponse
from utils.response_code import Code
import json
from datetime import datetime
import logging


logger = logging.getLogger("django")


# Create your views here.
def index(request):
    if not request.user.is_authenticated:

        return redirect("/login/")
    return render(request, "xadmin/news/index.html")


class TagManageView(View):
    def get(self, request):
        tags = Tag.objects.values("id", "name").annotate(num_news=Count("news")).filter(is_delete=False).order_by("-num_news")
        return render(request, "xadmin/news/tags_manage.html", context={"tags": tags})

    def post(self, request):
        json_str = request.body
        if json_str:
            data = json.loads(json_str)
            print(data)
            tag_name = data.get("name")
            if not tag_name:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签名不能为空")
            else:
                tag_name = tag_name.strip()
                # 保存数据到数据库
                tag, flag = Tag.objects.get_or_create(name=tag_name)
                if flag:
                    return ResultResponse(errmsg=Code.OK)
                else:
                    # 如果数据库中存在这个分类
                    if tag.is_delete:
                        tag.is_delete = False
                        tag.save(update_fields=["is_delete"])
                        return ResultResponse(errno=Code.OK)
                    else:
                        return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签名已存在")

        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

    def put(self, request, tag_id):
        json_str = request.body
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        data = json.loads(json_str)
        tag_name = data.get("name")

        tag = Tag.objects.only("id").filter(id=tag_id).first()
        if tag:
            if tag_name and tag_name.strip():
                if not Tag.objects.only("id").filter(name=tag_name).first():
                    tag.name = tag_name
                    tag.save(update_fields=["name"])
                    return ResultResponse(errno=Code.OK)
                else:
                    return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签名已存在")
            else:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签名为空")
        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="修改的标签不存在")

    def delete(self, request, tag_id):
        tag = Tag.objects.only("id").filter(id=tag_id).first()
        if not tag:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签不存在")
        if tag.is_delete:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="标签已删除")
        else:
            tag.is_delete = True
            tag.save(update_fields=["is_delete"])
            return ResultResponse(errno=Code.OK)


class HotNewsManageView(View):
    def get(self, request):
        hotNews = HotNews.objects.select_related("news").only("id", "news__title", "news__tag__name", "priority").\
            filter(is_delete=False).order_by("priority")
        print(hotNews)
        return render(request, 'xadmin/news/hot_news_manage.html', context={"hotNews": hotNews})

    def post(self, request, hot_news_id):
        json_str = request.body
        if json_str:
            data = json.loads(json_str)
            print(data)
            priority = data.get("priority", 0)
            priority = int(priority)
            hot_news = HotNews.objects.only("id", "priority").filter(id=hot_news_id, is_delete=False).first()
            if hot_news:
                print(type(priority))
                if priority and int(priority) in [1, 2, 3, 4, 5] and priority != hot_news.priority:
                    print(hot_news.priority, priority)
                    hot_news.priority = priority
                    hot_news.save(update_fields=["priority"])
                    return ResultResponse(errno=Code.OK, errmsg="修改成功")
                else:
                    print(hot_news.priority, priority)
                    return ResultResponse(errno=Code.ERRPARAMS, errmsg="优先级设置有误")
            else:
                ResultResponse(errno=Code.ERRPARAMS, errmsg="找不到要修搞的热门文章")
        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

    def delete(self, request, hot_news_id):
        obj = HotNews.objects.only("id").filter(id=hot_news_id, is_delete=False).first()
        if obj:
            obj.is_delete = True
            obj.save(update_fields=["is_delete"])
            return ResultResponse(errno=Code.OK, errmsg="删除成功")

        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="删除的数据不存在")


class HotNewsAddView(View):
    def get(self, request):
        tags = Tag.objects.only("id", "name").all()
        priority_dict = dict(HotNews.choices)
        return render(request, "xadmin/news/hot_news_add.html", context={"tags": tags, "priority_dict": priority_dict})

    def post(self, request):
        json_str = request.body
        if json_str:
            print(json.loads(json_str))
            try:
                data = json.loads(json_str)

            except:
                print("Hello")
                raise Http404()
            _id = int(data.get("id"))
            objs = News.objects.values('id', 'title').filter(tag__id=_id, is_delete=False)
            news_list = [i for i in objs]
            print(news_list)
            if objs:
                return ResultResponse(errno=Code.OK, data={"news_list": news_list})
            else:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

    def put(self, request):
        json_str = request.body
        if json_str:
            pass
        else:
            pass


class NewsManageView(View):
    def get(self, request):
        '''
        title, author, tag, update_time
        :param request:
        :return:
        '''

        start_time = request.GET.get("start_time", "")
        start_time = datetime.strptime(start_time, "%Y/%m/%d") if start_time else ""

        end_time = request.GET.get('end_time', '')
        end_time = datetime.strptime(end_time, '%Y/%m/%d') if end_time else ""

        newses = News.objects.only("title", "author", "tag__name", "update_time").filter(is_delete=False)

        if start_time and not end_time:
            newses = newses.filter(update_time__gte=start_time)

        if end_time and not start_time:
            newses = newses.filter(update_time__lte=end_time)

        if start_time and end_time:
            newses = newses.filter(update_time__range=(start_time, end_time))

        title = request.GET.get('title', '')
        if title:
            newses = newses.filter(title__icontains=title)

        author_name = request.GET.get('author_name', '')
        if author_name:
            newses = newses.filter(author__username__icontains=author_name)

        tags = Tag.objects.only('name').filter(is_delete=False)
        tag_id = int(request.GET.get('tag_id', 0))

        newses = newses.filter(is_delete=False, tag_id=tag_id) or newses.filter(is_delete=False)

        try:
            page = int(request.GET.get("page", 1))
        except Exception as e:
            logger.info("页面错误")
            page = 1

        pt = Paginator(newses, 6)

        try:
            news_info = pt.page(page)
        except EmptyPage:
            logger.info('页码错误')
            news_info = pt.page(pt.num_pages)

        # 自定义分页器
        pages_data = get_page_data(pt, news_info)
        # 把日期格式转 字符串格式
        start_time = start_time.strftime('%Y/%m/%d') if start_time else ''
        end_time = end_time.strftime('%Y/%m/%d') if end_time else ''

        data = {
            'news_info': news_info,
            'tags': tags,
            'paginator': pt,
            'start_time': start_time,
            'end_time': end_time,
            'title': title,
            'author_name': author_name,
            'tag_id': tag_id,
            'other_param': urlencode({
                'start_time': start_time,
                'end_time': end_time,
                'title': title,
                'author_name': author_name,
                'tag_id': tag_id,

            })
        }
        data.update(pages_data)

        return render(request, 'xadmin/news/news_manage.html', context=data)

    def delete(self, request, news_id):
        _id = news_id
        news = News.objects.only("id").filter(id=_id, is_delete=False).first()
        if _id and news:
            news.is_delete = True
            news.save(update_fields=["is_delete"])
            return ResultResponse(errno=Code.OK, errmsg="删除成功")
        else:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

def get_page_data(pt,current_page,around_count=3):
    """
    分页对象  单前页   总页数
    :return:
    """
    current_page_num = current_page.number  # 1
    # 获取总也码数
    total_page_num = pt.num_pages   # 1--100

    # 默认左右两边都没有页码
    left_more_page = False
    right_more_page = False

    # 计算左边的值
    left_start_index = current_page_num- around_count  # -3
    left_end_index = current_page_num
    if current_page_num <= around_count * 2 + 1:
        left_page_range = range(1,left_end_index)
    else:
        left_more_page = True
        left_page_range = range(left_start_index,left_end_index)

    # 搞右边  页码
    right_start_index = current_page_num + 1  # 2
    right_end_index = current_page_num + around_count + 1
    if current_page_num >= total_page_num - around_count * 2:
        right_page_range = range(right_start_index,total_page_num+1)
    else:
        right_more_page = True
        right_page_range = range(right_start_index,right_end_index)

    return {
        'current_page_num':current_page_num,

        # 页码总数
        'total_page_num':total_page_num,
        # 左标记
        'left_has_more_page':left_more_page,
        # 右标记
        'right_has_more_page':right_more_page,
        # 左范围
        'left_page_range':left_page_range,
        # 右范围
        'right_page_range':right_page_range
    }


class NewsEdit(View):
    def get(self, request, news_id):
        news = News.objects.filter(is_delete=False, id=news_id).first()
        tags = Tag.objects.only("name").filter(is_delete=False)
        if news:
            data = {
                "news": news,
                "tags": tags,
            }
        return render(request, "xadmin/news/news_edit.html", context=data)

    def put(self, request, news_id):
        # 判断修改的文章是否存在
        news = News.objects.filter(id=news_id).first()
        if not news:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        json_str = request.body
        # 判断修改内容是否存在
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        # 获取更新内容
        data = json.loads(json_str)

        # 过滤
        from .forms import NewsEditForm
        form = NewsEditForm()
        if form.is_valid():
            news.title = form.cleaned_data.get("title")
            news.digest = form.cleaned_data.get('digest')
            news.tag = form.cleaned_data.get('tag')
            news.image_url = form.cleaned_data.get('image_url')
            news.content = form.cleaned_data.get('content')
            news.save()
            return ResultResponse(errmsg='文章更新成功')
        else:
            err_list = []
            for err in form.errors.values():
                err_list.append(err)
            return ResultResponse(err=Code.ERRVERIFY, errmsg="/".join(err_list))


class NewsPub(View):
    def get(self, request):
        tags = Tag.objects.only("name").filter(is_delete=False)
        return render(request, "xadmin/news/news_edit.html", context={"tags": tags})

    def post(self, request):
        json_str = request.body
        # 判断发布内容是否存在
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        # 获取发布内容
        data = json.loads(json_str)

        # 过滤
        from .forms import NewsEditForm
        form = NewsEditForm()
        if form.is_valid():
            news = News()
            for k, v in form.cleaned_data:
                setattr(news, k, v)
            # news.title = form.cleaned_data.get("title")
            # news.digest = form.cleaned_data.get('digest')
            # news.tag = form.cleaned_data.get('tag')
            # news.image_url = form.cleaned_data.get('image_url')
            # news.content = form.cleaned_data.get('content')
            news.save()
            return ResultResponse(errmsg='文章发布成功')
        else:
            err_list = []
            for err in form.errors.values():
                err_list.append(err[0])
            return ResultResponse(err=Code.ERRVERIFY, errmsg="/".join(err_list))


class BannerManager(View):
    def get(self, request):
        banners = Banner.objects.filter(is_delete=False)
        priority_dict = OrderedDict(Banner.choices)
        print(priority_dict)
        return render(request, "xadmin/banner/banner_manage.html", context=locals())


class BannerEdit(View):
    def put(self, reqeust, banner_id):
        banner = Banner.objects.only("id").filter(id=banner_id, is_delete=False).first()
        if not banner:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        json_str = reqeust.body
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        data = json.loads(json_str)

        priority = int(data.get("priority"))
        priority_list = [i for i, _ in Banner.choices]
        if priority not in priority_list:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="优先级不存在")
        image_url = data["image_url"]
        if not image_url:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="图片数据为空")
        if banner.priority == priority and banner.image_url == image_url:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="数据没有修改")
        # 保存到数据库
        banner.priority = priority  # 1 2 3 4  5 6  看他的值
        banner.image_url = image_url

        banner.save(update_fields=['priority', 'image_url'])
        return ResultResponse(errno=Code.ERRPARAMS, errmsg="轮播图更新成功")

    def delete(self, request, banner_id):
        banner = Banner.objects.only("id").filter(id=banner_id, is_delete=False).first()
        if not banner:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        try:
            banner.delete()
        except Exception as e:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="网络出现问题")
        else:
            return ResultResponse(errmsg="删除成功")


class BannerPubView(View):
    def get(self, request):
        """
                js 触发  传图片的视图    关联文章视图

                :param request:
                :return:
                """
        tags = Tag.objects.values('id', 'name').annotate(num_news=Count('news')).filter(is_delete=False)

        pri = OrderedDict(Banner.B_CHOICES)
        return render(request, 'xadmin/banner/banner_pub.html', context={'tags': tags, 'priority_dict': pri})

    def post(self, request):
        pass


def image_upload(request):
    if request.method == "POST":
        file = request.FILES.get("image_file", None)
        if file:
            image_file = file
            try:
                print(image_file)
                filename = image_file.name
                ext = filename.split(".")[-1]
            except Exception as e:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="上传文件未接收到")
            if ext not in ["jpg", "jpeg", "gif", "png", "bmp", "webp"]:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="请上传图片文件")

            from utils.fastdfs.fdfs import client
            try:
                response = client.upload_by_buffer(image_file.read(), file_ext_name=ext)
                if "successed" not in response.get("Status"):
                    raise Exception("文件上传失败")
            except Exception as e:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="文件上传失败")
            from dj32_test.settings.dev import FDFS_DOMAIN
            image_url = FDFS_DOMAIN + response.get("Remote file_id")
            return ResultResponse(errno=Code.OK, data={"image_url": image_url})
        else:
            text_file = request.FILES.get("text_file", None)
            if text_file:
                print(text_file.name)
                try:
                    filename, ext = text_file.name.split(".")
                except:
                    return ResultResponse(errno=Code.ERRPARAMS, errmsg="文件没有扩展名")
                if text_file.content_type not in ('application/zip', 'application/pdf','text/plain'):
                    return ResultResponse(errno=Code.ERRPARAMS, errmsg="不能上传非文档文件")
                from utils.baiduyun import upload
                try:
                    access_url = upload(text_file.name, text_file.read(), bucket_name="pdf-home")
                except Exception as e:
                    return ResultResponse(errno=Code.ERRPARAMS, errmsg="文件上传失败")
                return ResultResponse(errno=Code.OK, data={"text_url": access_url})

            else:
                return ResultResponse(errno=Code.ERRPARAMS, errmsg="上传文件未接收到")
    else:
        return Http404()


class MarkDownUploadImage(View):
    def post(self, request):
        file = request.FILES.get("editormd-image-file")
        # 判断是否存在
        if not file:
            fail = {
                "success": 0,
                "message": "上传失败"
            }
            return JsonResponse(data=fail)
        # 判断上传的文件类型是否正确
        if file.content_type not in ('image/jpeg', 'image/png', 'image/gif'):
            fail = {
                "success": 0,
                "message": "不能上传非图片文件"
            }
            return JsonResponse(data=fail)
        # 判断文件是否加个扩展名，否则就自动加入
        try:
            ext = file.name.split(".")[-1]
        except Exception as e:
            ext = "jpg"

        # 开始上传
        from utils.fastdfs.fdfs import client
        try:
            res = client.upload_by_buffer(file.read(), file_ext_name=ext)
        except Exception as e:
            fail = {
                "success": 0,
                "message": "图片上传出现异常"
            }
            return JsonResponse(data=fail)
        else:
            if "success" not in res.get("Status"):
                fail = {
                    "success": 0,
                    "message": "上传失败"
                }
                return JsonResponse(data=fail)
            else:
                from dj32_test.settings.dev import FDFS_DOMAIN
                image_name = res.get("Remote file_id")
                access_url = FDFS_DOMAIN + image_name
                return JsonResponse(data={"success": 1, "message": "上传成功", "url": access_url})


class DocManageView(View):
    def get(self, request):
        docs = Doc.objects.filter(is_delete=False)
        return render(request, "xadmin/doc/doc_manage.html", context={"docs": docs})


class DocEditView(View):
    def get(self, request, doc_id):
        doc = Doc.objects.filter(is_delete=False, id=doc_id).first()
        if doc:
            return render(request, 'xadmin/doc/doc_edit.html', locals())
        else:
            return HttpResponseNotFound('PAGE NOT FOUND')

    def put(self, request, doc_id):
        doc = Doc.objects.filter(id=doc_id, is_delete=False).first()
        if not doc:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg='参数错误')
        js_str = request.body
        js_str = json.loads(js_str)
        from xadmin.forms import DocEditForm
        form = DocEditForm(js_str)
        if form.is_valid():
            for k, v in form.cleaned_data.items():
                setattr(doc, k, v)
            doc.save()
            return ResultResponse(errmsg='文档信息编辑成功')
        else:
            err_list = []
            for err in form.errors.values():
                err_list.append(err[0])
            return ResultResponse(err=Code.ERRVERIFY, errmsg="/".join(err_list))

    def delete(self, request, doc_id):
        doc = Doc.objects.only("id").filter(id=doc_id).first()
        if not doc:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="文档不存在")
        if doc.is_delete:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="文档已删除")
        else:
            doc.is_delete = True
            doc.save(update_fields=["is_delete"])
            return ResultResponse(errno=Code.OK)


class DocPubView(View):
    def get(self, request):
        return render(request, 'xadmin/doc/doc_edit.html', locals())

    def post(self, request):
        js_str = request.body
        js_str = json.loads(js_str)
        from xadmin.forms import DocPubForm
        form = DocPubForm(js_str)
        if form.is_valid():
            doc = Doc()
            for k, v in form.cleaned_data.items():
                setattr(doc, k, v)
            doc.author_id = request.user.id
            doc.save()
            return ResultResponse(errmsg='文档上传成功')
        else:
            err_list = []
            for err in form.errors.values():
                err_list.append(err[0])
            return ResultResponse(err=Code.ERRVERIFY, errmsg="/".join(err_list))


class CourseManageView(View):
    def get(self, request):
        courses = Course.objects.select_related("teacher", "category").only("title", "category__name", "teacher__name"
                                                                            ).filter(is_delete=False)
        return render(request, "xadmin/course/course_manage.html", locals())


class CourseEditView(View):
    def get(self, request, *args, **kwargs):
        course_id = kwargs.get("c_id")
        if not course_id:
            return Http404()
        course = Course.objects.filter(id=course_id, is_delete=False).first()
        categories = CourseCategory.objects.filter(is_delete=False)
        teachers = Teacher.objects.filter(is_delete=False)
        print(course, categories, teachers)
        return render(request, "xadmin/course/course_pub_or_edit.html", locals())


class CoursePubView(View):
    def get(self, request):
        categories = CourseCategory.objects.filter(is_delete=False)
        teachers = Teacher.objects.filter(is_delete=False)
        return render(request, "xadmin/course/course_pub_or_edit.html")

    def post(self, request):
        json_str = request.body
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        try:
            course = json.loads(json_str)
        except Exception as e:
            print(e)
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")


from django.contrib.auth.models import Group, Permission
from django.db.models import Count


class GroupManageView(View):
    def get(self, request):
        groups = Group.objects.only("id", "name").annotate(num_users=Count("user")).order_by("num_users")

        return render(request, "xadmin/group/group_manage.html", locals())


class GroupAddView(View):
    def get(self, request):
        permissions = Permission.objects.all()
        return render(request, "xadmin/group/group_add.html", locals())

    def post(self, request):
        json_str = request.body
        if not json_str:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        data = json.loads(json_str)

        group_name = data.get("name").strip()
        if not group_name:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="组名为空")
        group, is_created = Group.objects.get_or_create(name=group_name)
        if not is_created:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="组名已存在")

        group_permissions = data.get('group_permission')
        if not group_permissions:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="权限参数为空")
        try:
            permissions_set = set(group_permissions)
        except Exception as e:
            logger.info('传的权限参数异常：\n{}'.format(e))
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="权限参数异常")
        all_permissions_set = set(i.id for i in Permission.objects.only('id'))
        if not permissions_set.issubset(all_permissions_set):
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="有不存在的权限参数")
        # 设置权限
        for perm_id in permissions_set:
            p = Permission.objects.get(id=perm_id)
            group.permissions.add(p)
        group.save()
        return ResultResponse(errno=Code.ERRPARAMS, errmsg="组创建成功")


from django.http import HttpResponseForbidden


class GroupEditView(View):
    def get(self, request, group_id):
        group = Group.objects.filter(id=group_id).first()
        if not group:
            return HttpResponseForbidden()
        permissions = Permission.objects.filter()
        return render(request, "xadmin/group/group_add.html", locals())

    def put(self, request, group_id):
        group = Group.objects.filter(id=group_id).first()
        if not group:
            return HttpResponseForbidden()
        js_str = request.body
        dict_data = json.loads(js_str)
        g_name = dict_data.get('name', '').strip()
        if not g_name:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")
        if g_name != group.name and Group.objects.filter(name=g_name).exists():
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="组名存在")
        g_permission = dict_data['group_permission']  # [1,2,3,4,5]
        if not g_permission:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="参数错误")

        per_set = set(i for i in g_permission)  #

        db_per_set = set(i.id for i in group.permissions.all())

        if per_set == db_per_set:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="用户没有修改权限")
        group.permissions.clear()

        # 设置权限 保存
        for i in per_set:
            p = Permission.objects.get(id=i)
            group.permissions.add(p)

        group.name = g_name
        group.save()

        return ResultResponse(errmsg="组创建成功")

    def delete(self, request, group_id):
        g = Group.objects.filter(id=group_id).first()
        if g:
            g.permissions.clear()
            g.delete()
            return ResultResponse(errmsg='删除成功')
        else:
            return HttpResponseForbidden()


from users.models import User


class UserManageView(View):
    def get(self, request):
        users = User.objects.only("username", "is_staff", "is_superuser").filter(is_active=True)
        groups = Group.objects.all()
        return render(request, "xadmin/group/user_manage.html", locals())


class UserEditView(View):
    def get(self, request, user_id):
        user_instance = User.objects.filter(id=user_id).first()
        if not user_instance:
            return HttpResponseForbidden()

        groups = Group.objects.only("name").all()

        return render(request, "xadmin/group/user_edit.html", locals())

    def delete(self, request, user_id):
        user = User.objects.filter(id=user_id).first()
        print(user)
        # 多对多关联的用户在删除前先解除关联
        if not user:
            return ResultResponse(errno=Code.ERRPARAMS, errmsg="要删除的用户不存在")
        user.groups.clear()
        user.user_permissions.clear()
        user.is_active = False
        user.save()
        return ResultResponse(errmsg="删除成功")

    def put(self, request, user_id):
        user_instance = User.objects.filter(id=user_id).first()
        if not user_instance:
            return ResultResponse(errno=Code.NODATA, errmsg='无数据')

        json_str = request.body
        if not json_str:
            return ResultResponse(errno=Code.PARAMERR, errmsg="参数错误")

        dict_data = json.loads(json_str)
        try:
            groups = dict_data.get('groups')
            is_superuser = int(dict_data['is_superuser'])  # 0
            is_staff = int(dict_data.get('is_staff'))  # 1
            is_active = int(dict_data['is_active'])  # 1
            params = (is_active, is_staff, is_superuser)
            if not all([q in (0, 1) for q in params]):
                return ResultResponse(errno=Code.PARAMERR, errmsg='参数错误')
        except Exception as e:
            logger.info('从前端获取得用户参数错误{}'.format(e))
            return ResultResponse(errno=Code.PARAMERR, errmsg='参数错误')

        try:
            if groups:
                groups_set = set(int(i) for i in groups)
            else:
                groups_set = set()
        except Exception as e:
            logger.info('用户组参数异常{}'.format(e))
            return ResultResponse(errno=Code.PARAMERR, errmsg='用户组参数异常')

        # 组
        all_groups_set = set(i.id for i in Group.objects.only('id'))
        # 判断前台传得组是否在所有用户组里面
        if not groups_set.issubset(all_groups_set):
            return ResultResponse(errno=Code.PARAMERR, errmsg='有不存在的用户组参数')

        gsa = Group.objects.filter(id__in=groups_set)  # [1,3,4]

        # 保存
        user_instance.groups.clear()
        user_instance.groups.set(gsa)
        user_instance.is_staff = bool(is_staff)
        user_instance.is_superuser = bool(is_superuser)
        user_instance.is_active = bool(is_active)
        user_instance.save()
        return ResultResponse(errmsg='用户组更新成功')

    def delete(self, request, user_id):
        user_instance = Users.objects.filter(id=user_id).first()
        if user_instance:
            user_instance.groups.clear()  # 去除用户组
            user_instance.user_permissions.clear()  # 清楚用户权限
            user_instance.is_active = False
            user_instance.save()
            return ResultResponse(errmsg='用户删除成功')
        else:
            self.data = ResultResponse(errno=Code.PARAMERR, errmsg='需要删除的用户不存在')
            return self.data


